package chat.user.dao;

import java.sql.Connection;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanListHandler;
import org.apache.commons.dbutils.handlers.MapListHandler;

import com.mchange.v2.c3p0.ComboPooledDataSource;

import chat.user.domain.Info;
import chat.user.domain.User;
import cn.itcast.commons.CommonUtils;

public class InfoDao {
	ComboPooledDataSource dataSource = new ComboPooledDataSource();
	QueryRunner qr = new QueryRunner(dataSource);
	
	
	public void addInfo(Info info) {
		try 
		{
			Connection conn = dataSource.getConnection();
			String sql = "insert into info values(?,?,?,?,?)";
			qr.update(conn, sql, info.getId(),info.getUser().getId(),info.getSendtime(),
					info.getContent(),info.getIp());
			
			
		} catch (SQLException e) 
		{
			throw new RuntimeException(e);
		}
	}


	public List<Info> selectInfo() {
		try 
		{
			
			String sql = "select * from info,user where info.uid=user.id order by info.id asc";
			
			List<Map<String,Object>> mapList = qr.query(sql, new MapListHandler());
			
			
			return toBeanList(mapList);
			
		} catch (SQLException e) 
		{
			throw new RuntimeException(e);
		}
		
	}


	private List<Info> toBeanList(List<Map<String, Object>> mapList) {
		List<Info> infoList = new ArrayList<Info>();
		for(Map<String,Object> map : mapList)
		{
			infoList.add(toBean(map));
		}
		return infoList;
	}


	private Info toBean(Map<String, Object> map) {
		Info info = CommonUtils.toBean(map, Info.class);
		User user = CommonUtils.toBean(map, User.class);
		info.setUser(user);
		return info;
	}
	
}
